import akshare as ak
import pandas as pd
from datetime import datetime

# ===== 宏定义区域 =====
# 您可以在这里修改这些参数
STOCK_SYMBOL = "600519"  # 股票代码
PERIOD = "daily"         # 周期: "daily"表示日线
START_DATE = "20230101"  # 开始日期
OUTPUT_FILENAME = "maotai_data"  # 输出文件名(不需要扩展名)
# =====================

def fetch_stock_data_akshare(symbol, period, start_date):
    try:
        # 获取股票数据
        data = ak.stock_zh_a_hist(symbol=symbol, 
                                 period=period, 
                                 start_date=start_date, 
                                 end_date=datetime.now().strftime("%Y%m%d"),
                                 adjust="qfq")
        
        if data.empty:
            print("未获取到数据，请检查股票代码和日期范围")
            return None
            
        # 重命名列
        data.rename(columns={
            '日期': 'date',
            '开盘': 'open',
            '最高': 'high',
            '最低': 'low',
            '收盘': 'close',
            '成交量': 'volume'
        }, inplace=True)
        
        # 转换日期格式
        data['date'] = pd.to_datetime(data['date'])
        
        # 重置索引
        data.reset_index(drop=True, inplace=True)
        
        return data[['date', 'open', 'high', 'low', 'close', 'volume']]
        
    except Exception as e:
        print(f"获取数据时出错: {str(e)}")
        return None

# 获取数据
stock_data = fetch_stock_data_akshare(STOCK_SYMBOL, PERIOD, START_DATE)

if stock_data is not None:
    # 显示数据基本信息
    print(f"获取了从 {START_DATE} 到 {datetime.now().strftime('%Y-%m-%d')} 的股票数据 (代码: {STOCK_SYMBOL})")
    print(f"数据形状: {stock_data.shape}")
    print("\n前5行数据:")
    print(stock_data.head())
    
    # 保存为CSV文件
    filename = f"{OUTPUT_FILENAME}_{STOCK_SYMBOL}_{START_DATE}_{datetime.now().strftime('%Y%m%d')}.csv"
    stock_data.to_csv(filename, index=False)
    print(f"\n数据已保存到: {filename}")
else:
    print(f"未能获取股票数据 (代码: {STOCK_SYMBOL})")